package Offer2018.java8;

import org.junit.Test;

import java.util.Optional;

/**
 *  Optional.of(T t) : 创建一个 Optional 实例，t必须非空;
 *  Optional.empty() : 创建一个空的 Optional 实例
 *  Optional.ofNullable(T t):t可以为null
 */
public class OptionalTest {

    @Test
    public void test1() {
        Girl girl = null;
        Optional<Girl> optional = Optional.of(girl);
    }

    @Test
    public void test2() {
        Girl girl = null;
        Optional<Girl> optional = Optional.empty();
    }

    @Test
    public void test3() {
        Girl girl = null;
        Optional<Girl> optional = Optional.ofNullable(girl);
        System.out.println(optional);
    }

    public String getGirlName(Boy boy) {
        return boy.getGirl().getName();
    }

    @Test
    public void test4() {
        Boy boy = new Boy();//girl为null
        System.out.println(getGirlName(boy));
    }

    /**
     * 优化
     *x
     * @param boy
     * @return
     */
    public String getGirlName1(Boy boy) {
        if (boy != null) {
            Girl girl = boy.getGirl();
            if (girl != null) {
                return boy.getGirl().getName();
            }
        }
        return null;
    }

    @Test
    public void test5() {
        Boy boy = new Boy();//girl为null
        System.out.println(getGirlName1(boy));
    }


    /**
     * 使用Optional
     *
     * @param boy
     * @return
     */
    public String getGirlName2(Boy boy) {
        Optional<Boy> optionalBoy = Optional.ofNullable(boy);
        //如果boy为null则使用指定的other对象。
        Boy boy1 = optionalBoy.orElse(new Boy(new Girl("刘亦菲")));

        Girl girl = boy1.getGirl();
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);

        //如果girl为null则使用指定的other对象。
        Girl girl1 = optionalGirl.orElse(new Girl("隋东风"));
        return girl1.getName();
    }

    @Test
    public void test6() {
        Boy boy = new Boy();//boy不为null ，girl为null
        System.out.println(getGirlName2(boy));//隋东风

        Boy boy2 = null;//boy为null ，girl为null
        System.out.println(getGirlName2(boy2));//刘亦菲

        Boy boy3 = new Boy(new Girl("貂婵"));//boy不为null ，girl不为null
        System.out.println(getGirlName2(boy3));//貂婵
    }

}
